#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""File reader module"""

__author__ = "Lei Chen <hide1713@gmail.com>"
import logging

from genome_exception import GReadFileException
from data_model.genome_record import GenomeRecord
from data_model.cog_model import CogModel
import os.path

class TextFileReader(object):
    """Read text file and generate Cog model.
    The start_pos and end_pos columns are omitted
    Input format: reads_name start_position end_position start_pos end_pos e-value
    Example:
    gnl|ti|1565709966:0:0  COG1438 29  64  3 38 7.9e-08
    gnl|ti|1564540259:1:0  COG1438 33  55  3 25 2.9e-05
    gnl|ti|1565662757:4:0  COG1438 29  58  2 31 0.0001
    gnl|ti|1565771157:4:0  COG1438 29  58  2 31 0.0001
    gnl|ti|1565787164:4:0  COG1438 29  58  2 31 0.0001
    gnl|ti|1565699970:0:0  COG1438 29  56  3 30 0.00033

    """
    
    def __init__(self):
        """Constructor
        """
        self.log = logging.getLogger(self.__class__.__name__)

    def read_file(self, file_path):
        """Return a list of genome records
        
        Arguments:
        - `file_path`: the path of the data file
        """
        records = []
        line_num = 0
        base_name = os.path.basename(file_path)
        file=open(file_path, 'r')
        if file:
            self.log.info("Loading File:"+file_path)
            line = file.readline()
            try:
                if line.startswith("Reads"):
                    #First line is title
                    pass
                else:
                    line_num = 1
                    rec = self.generate_genome_record(line)
                    records.append(rec)
                for line in file:
                    line_num += 1
                    rec = self.generate_genome_record(line)
                    records.append(rec)
            except (ValueError, IndexError):
                self.log.error("Fail to load file "+file_path)
                raise GReadFileException(file_path, line_num, line)
            self.log.debug("File Loaded")
        file.close()
        return records

    def generate_genome_record(self, line):
        """Return a GenomeRecord object
        
        Arguments:
        - `line`: is a string
        """
        field = line.split()
        assert(len(field)==7),(line,"Record should have 7 columns")
        read = field[0]
        cog = field[1]
        start = int(field[2])
        end = int(field[3])
        value = float(field[6])
        return GenomeRecord(read, cog, start, end, value)
        
    def generate_model(self, file_path, cog_map):
        """Create data model.
        
        Arguments:
        - `file_path`: the path of the data file
        - `cog_map`: is the cog family map
        """
        records = self.read_file(file_path)
        base_name = os.path.basename(file_path)
        model = CogModel(base_name, cog_map)
        model.add_genome_records(records)
        return model
